<!-- engineering-img.vue -->
<template>
  <view class="custom-layout">
	  <wd-collapse v-model="value" class="list" v-if="engineeringNodeTree.length>0">
	    <wd-collapse-item
	      v-for="(firstLevel, index) in engineeringNodeTree"
	      :key="firstLevel.id"
	      :title="firstLevel.stageName"
	      :name="`first${firstLevel.id}`"
	    >
        <template #title="{ expanded, disabled, isFirst }">
          <view class="header">
            <text >{{ firstLevel.stageName }}</text>
            <view @click.stop="handleOpenExamine(firstLevel.children)" v-if="hasItemsNeedingApproval(firstLevel.children)">
               <wd-button type="text">审核</wd-button>
            </view>
       
            
          </view>
           
        </template>
          <!-- 第二层 -->
        	  <wd-collapse v-model="collapseList" class="list">
	            <wd-collapse-item
	              v-for="secondLevel in firstLevel.children"
	              :key="secondLevel.id"
	              :title="secondLevel.stageName"
	              :name="`eng${secondLevel.id}`"
	            >
                <template #title="{ expanded, disabled, isFirst }">
                  <view class="header">
                    <text >{{ secondLevel.stageName }}</text>
                   
           
           

                  </view>
                 
                </template>
                         <!-- 第三层 -->
                <wd-collapse v-model="third" class="list">
	            <wd-collapse-item
	              v-for="thirdLevel in secondLevel.children"
	              :key="thirdLevel.id"
	              :title="thirdLevel.stageName"
	              :name="`third${thirdLevel.id}`"
	            >
                <template #title="{ expanded, disabled, isFirst }">
                  <view class="header-wrap">
                    <view class="left-group">
                      <text class="name">{{ thirdLevel.stageName }}</text>
                      <wd-tag :type="getTagThemeAndLabel(thirdLevel.imgApprovalStatus - 1).theme">
                        {{getTagThemeAndLabel(thirdLevel.imgApprovalStatus - 1).label}}
                      </wd-tag>
                    </view>
                    <div class="upload-date" v-if="thirdLevel.completeStatus === '1'">
                      上传日期：{{JSON.parse(thirdLevel.fileUrl)[0].uploadTime }}
                    </div>
                  </view>
                </template>
              <template v-for="(file2, index2) in JSON.parse(thirdLevel.fileUrl)" :key="index2">
                <file-preview :file="file2"  />
              </template>
              <wd-button 
                v-if="thirdLevel.imgApprovalStatus=='3'&&hasPermission('system:engineering-stage:re-upload-engineering-stage-picture')" 
                @click="handleReUpload(thirdLevel)"
              >重新上传</wd-button>


	            </wd-collapse-item>
	              </wd-collapse>

	            </wd-collapse-item>
	          </wd-collapse>
	        </wd-collapse-item>
	      </wd-collapse>

	  <!-- 空状态 -->
	  <wd-status-tip v-else image="search" tip="暂无数据" />
      </view>
</template>
<script setup>
import dayjs from 'dayjs';	
import { ref, computed, watch, onMounted, reactive, nextTick } from 'vue';
import { onReady } from '@dcloudio/uni-app';
import {
  useDictionaryStore,
  useUserStore,
  usePermissionStore 
} from '@/store/index.js'
import FilePreview from '@/packageA/components/file-preview/file-preview.vue';
import { getEngineeringStageList,getEngineeringTeamUsers } from '@/api/engineering/detail.js'
import listToTree from '@/utils/listToTree';
const props = defineProps({
  // 订单id
  engineeringId: {
    type: Number,
    required: true
  },
   companyId: {
    type: Number,
    required: true
  },
  
});

// 字典仓库
 const dictionaryStore = useDictionaryStore()
 // 用户仓库
 const userStore = useUserStore()
// 权限参数
const permissionStore = usePermissionStore()
const hasPermission = (permissions) => {
	console.log(permissionStore.permissions,'permissions');
	console.log(permissionStore.hasPermission(permissions),'ll');
      return permissionStore.hasPermission(permissions)
    }

const value = ref(['first1'])
const collapseList = ref(['eng1'])
const third = ref(['third'])
// 根据审批状态获取标签样式以及文字
const getTagThemeAndLabel = (result) => {
  const map = [
    {
      theme: 'warning',
      label: '待审批',
    },
    {
      theme: 'success',
      label: '审批通过',
    },
    {
      theme: 'danger',
      label: '审批不通过',
    },
    {
      theme: 'danger',
      label: '审批已取消',
    },
  ];

  return result in map ? map[result] : { theme: 'default', label: '未知状态' };
};


// 施工节点
const engineeringNodeTree = ref([])
// 获取施工节点列表
const handleGetengineeringStageList = () => {

  const params = {
    pageSize: -1,
    engineeringId: props.engineeringId
  }
  getEngineeringStageList(params).then(data => {
    const tree = listToTree(data.list) 
    engineeringNodeTree.value = filterTreeWithImages(tree)


    
  }).catch((error) => {
    console.log(error);
    	// uni.showToast({
    	// 	title: '获取数据失败',
    	// 	icon: 'error'
    	// })
    })
}
// 过滤树，只保留有图片的节点
const filterTreeWithImages = (tree) => {
  return tree
    .map((firstLevel) => {
      // 复制第一层节点
      const firstLevelCopy = { ...firstLevel };
      // 过滤第二层
      firstLevelCopy.children = firstLevel.children
        ?.map((secondLevel) => {
          // 复制第二层节点
          const secondLevelCopy = { ...secondLevel };
          // 过滤第三层
          secondLevelCopy.children = secondLevel.children?.filter((thirdLevel) => {
            return (
              thirdLevel.uploadStatus === '1' &&
              thirdLevel.fileUrl &&
              JSON.parse(thirdLevel.fileUrl).length > 0
            );
          });
          // 如果第三层有数据，则保留第二层
          return secondLevelCopy.children?.length > 0 ? secondLevelCopy : null;
        })
        .filter(Boolean);
      // 如果第二层有数据，则保留第一层
      return firstLevelCopy.children?.length > 0 ? firstLevelCopy : null;
    })
    .filter(Boolean);
};
// 检查是否存在需要审核的节点
const hasItemsNeedingApproval = (secondLevelItems) => {
  return secondLevelItems.some(secondLevel => {
    return secondLevel.children?.some((thirdLevel) => {
      return thirdLevel.imgApprovalStatus == 1 && 
             thirdLevel.uploadStatus === '1' && 
             thirdLevel.fileUrl && 
             JSON.parse(thirdLevel.fileUrl).length > 0;
    });
  });
};
onMounted(async() => {
  handleGetengineeringStageList();
  uni.$on('refresh-examine', handleGetengineeringStageList)
  await nextTick();
});
// 跳转审核页面
const handleOpenExamine = (params) => {
  // 深拷贝参数避免修改原始数据
  const filteredParams = JSON.parse(JSON.stringify(params));
  
  // 过滤掉不需要审核的节点(imgApprovalStatus === 2)
  filteredParams.forEach((secondLevel) => {
    if (secondLevel.children) {
      secondLevel.children = secondLevel.children.filter((thirdLevel) => {
        return thirdLevel.imgApprovalStatus == 1 
      });
    }
  });
  
  // 只保留有需要审核子节点的二级节点
  const finalParams = filteredParams.filter((secondLevel) => {
    return secondLevel.children && secondLevel.children.length > 0;
  });

    uni.navigateTo({
		url: '/packageA/pages/project/engineeringImg/examine?row='+encodeURIComponent(JSON.stringify(finalParams))
	})
}
const handleReUpload = (thirdLevel) => {
 const params = {
    engineeringId:thirdLevel.engineeringId,
    id:thirdLevel.id,
    level:thirdLevel.level,
    parentId:thirdLevel.parentId,
    sort:thirdLevel.sort,
    stageName:thirdLevel.stageName,
    fileUrl:[]
  }
  uni.navigateTo({
		url: '/packageA/pages/project/engineeringImg/reUpload?row='+encodeURIComponent(JSON.stringify(params))
	})
}

</script>
<style lang="scss" scoped>
  .custom-layout {
	  min-height: calc(100vh - 430px);
    background-color: #fff;
  }
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .header-wrap {

    .left-group {
      // display: flex;
      align-items: center;
      flex: 1;
      min-width: 0;
      .name {
        margin-right: 2px;
      }

    }

    .upload-date {
      white-space: nowrap;
    }
  }


  .fz-14 {
    font-size: 14px;
    color: #9fa19f;
    display: flex;
    align-items: center;
  }
</style>